/**
 * Class: Repository
 *
 * Purpose: 
 *
 * Created: Jan 11, 2010 @ 10:41:39 PM
 * @author Ken Scott
 */
package org.openfantasia.util.misc;

import org.openfantasia.util.FileUtils;

import java.io.File;
import java.io.IOException;
import java.util.*;

public class Repository<T> {

	private PeriodicTask periodic;

	private boolean loaded = false;

	private boolean modified = false;

	private File file;

	private Map<String, T> objects = new HashMap<String, T>();


	private Repository() {
	}


	public Repository(File file, long savePeriod) {
		this.periodic = new PeriodicTask(savePeriod) {
			public void run() {
				try {
					Repository.this.store();
				}
				catch (IOException e) {
					e.printStackTrace();
				}
			}
		};
		this.file = file;
		this.periodic.start();
	}


	public synchronized void load() throws IOException, ClassNotFoundException {
		objects = (Map<String, T>) FileUtils.readObjectFromFile(file);
	}


	public synchronized void store() throws IOException {
		if(modified) {
			modified = false;
			if(!file.exists()) {
				file.mkdirs();
				file.createNewFile();
			}
			FileUtils.writeObjectToFile(file, objects);
		}
	}


	public synchronized T get(String id) {
		if(!loaded && file.exists()) {
			try {
				load();
				loaded = true;
			}
			catch (IOException iox) {
				iox.printStackTrace();
			}
			catch (ClassNotFoundException cnfx) {
				cnfx.printStackTrace();
			}
		}
		return objects.get(id);
	}


	public synchronized void put(String id, T object) throws IOException {
		objects.put(id, object);
		modified = true;
	}
}
